 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package com.hmdp;

 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.bean.copier.CopyOptions;
 import cn.hutool.core.lang.UUID;
 import com.hmdp.dto.UserDTO;
 import com.hmdp.entity.Shop;
 import com.hmdp.entity.User;
 import com.hmdp.service.IUserService;
 import com.hmdp.service.impl.UserServiceImpl;

 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import javax.annotation.Resource;
 import java.io.FileOutputStream;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;

 import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
 import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

 /**
  * <p>Project: hm-dianping-com.hmdp-GeneratorTaoken
  * <p>Powered by yishun On 2023-03-25 15:55:21
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @SpringBootTest
 public class GeneratorToken {

     @Autowired
     private IUserService userService;
     public static final String LOGIN_USER_KEY = "login:token:";
     @Resource
     private StringRedisTemplate stringRedisTemplate;
     @Test
     public void t1() {
         //查询全部用户
         List<User> users = userService.list(null);
         for (User user : users) {
             //随机生成token，作为登录令牌
             String token = UUID.randomUUID().toString(true);
             //将user对象转为hash存储
             UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
             Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                     CopyOptions.create()
                             .setIgnoreNullValue(true)
                             .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())
             );
             //保存登录数据到redis
             String tokenKey = LOGIN_USER_KEY + token;
             stringRedisTemplate.opsForHash().putAll(tokenKey, map);
             //设置有效期
             stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
             try (FileOutputStream fos = new FileOutputStream("token.txt",true)) {
                 fos.write(token.getBytes());
                 fos.write("\r\n".getBytes());
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }
 }
